<!DOCTYPE html>
<html lang=zh>
<head>
    <meta charset="utf-8">
    
    <title>第四章：使用QueryDSL与SpringDataJPA实现多表关联查询 | 恒宇少年De成长之路</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="对于业务逻辑复制的系统来说都存在多表关联查询的情况，查询的返回对象内容也是根据具体业务来处理的，我们本章主要是针对多表关联根据条件查询后返回单表对象，在下一章我们就会针对多表查询返回自定义的对象实体。">
<meta name="keywords" content="SpringBoot,QueryDSL">
<meta property="og:type" content="article">
<meta property="og:title" content="第四章：使用QueryDSL与SpringDataJPA实现多表关联查询">
<meta property="og:url" content="http://blog.yuqiyu.com/querydsl-chapter-4/index.html">
<meta property="og:site_name" content="恒宇少年De成长之路">
<meta property="og:description" content="对于业务逻辑复制的系统来说都存在多表关联查询的情况，查询的返回对象内容也是根据具体业务来处理的，我们本章主要是针对多表关联根据条件查询后返回单表对象，在下一章我们就会针对多表查询返回自定义的对象实体。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-cae4d81842fe54a6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-00533d0ae6859ba6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-df4c7dea32f63693.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-f1d4cb64234b160a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-01-23T16:10:58.966Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="第四章：使用QueryDSL与SpringDataJPA实现多表关联查询">
<meta name="twitter:description" content="对于业务逻辑复制的系统来说都存在多表关联查询的情况，查询的返回对象内容也是根据具体业务来处理的，我们本章主要是针对多表关联根据条件查询后返回单表对象，在下一章我们就会针对多表查询返回自定义的对象实体。">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/4461954-cae4d81842fe54a6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
    

    
        <link rel="alternate" href="/" title="恒宇少年De成长之路" type="application/atom+xml" />
    

    

    <link rel="stylesheet" href="/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/libs/open-sans/styles.css">
    <link rel="stylesheet" href="/libs/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="/libs/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/libs/justified-gallery/justifiedGallery.min.css">
    
    
    
    


</head>

<body>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/" id="logo">
                <i class="logo"></i>
                <span class="site-title">恒宇少年De成长之路</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/.">首页</a>
                
                    <a class="main-nav-link" href="/archives">时间轴</a>
                
                    <a class="main-nav-link" href="/categories">文章专题</a>
                
                    <a class="main-nav-link" href="/tags">标签云</a>
                
                    <a class="main-nav-link" href="/about">关于我</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="/css/images/avatar.png" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <!--button type="submit" class="search-form-submit"></button-->
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td ><a  class="main-nav-link" href="/.">首页</a></td>
                
                    <td ><a  class="main-nav-link" href="/archives">时间轴</a></td>
                
                    <td ><a  class="main-nav-link" href="/categories">文章专题</a></td>
                
                    <td ><a  class="main-nav-link" href="/tags">标签云</a></td>
                
                    <td ><a  class="main-nav-link" href="/about">关于我</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="/css/images/avatar.png" />
            <h2 id="name">恒宇少年</h2>
            <h3 id="title">Java软件工程师 &amp; 程序猿</h3>
            <span id="location"><i class="fa fa-map-marker"></i>山东, 济南</span>
            <a id="follow" target="_blank" href="https://www.jianshu.com/u/092df3f77bca">关注我</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                43
                <span>文章</span>
            </div>
            <div class="article-info-block">
                2
                <span>标签</span>
            </div>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="http://github.com/ppoffice/hexo-theme-icarus" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="twitter" class=tooltip>
                            <i class="fa fa-twitter"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="facebook" class=tooltip>
                            <i class="fa fa-facebook"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="dribbble" class=tooltip>
                            <i class="fa fa-dribbble"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
    </div>
</aside>

            
            <section id="main"><article id="post-querydsl-chapter-4" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
            <header class="article-header">
                
    
        <h1 class="article-title" itemprop="name">
            第四章：使用QueryDSL与SpringDataJPA实现多表关联查询
        </h1>
    

                
                    <div class="article-meta">
                        
    <div class="article-date">
        <i class="fa fa-calendar"></i>
        <a href="/querydsl-chapter-4/">
            <time datetime="2017-07-08T16:00:00.000Z" itemprop="datePublished">2017-07-09</time>
        </a>
    </div>


                        
    <div class="article-category">
    	<i class="fa fa-folder"></i>
        <a class="article-category-link" href="/categories/QueryDSL-核心技术/">QueryDSL 核心技术</a>
    </div>

                        
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/QueryDSL/">QueryDSL</a>, <a class="tag-link" href="/tags/SpringBoot/">SpringBoot</a>
    </div>

                    </div>
                
            </header>
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>对于业务逻辑复制的系统来说都存在多表关联查询的情况，查询的返回对象内容也是根据具体业务来处理的，我们本章主要是针对多表关联根据条件查询后返回单表对象，在下一章我们就会针对多表查询返回自定义的对象实体。<br><a id="more"></a></p>
<h1 id="本章目标"><a href="#本章目标" class="headerlink" title="本章目标"></a>本章目标</h1><p>基于SpringBoot框架平台完成SpringDataJPA与QueryDSL多表关联查询返回单表对象实例，查询时完全采用QueryDSL语法进行编写。</p>
<h1 id="构建项目"><a href="#构建项目" class="headerlink" title="构建项目"></a>构建项目</h1><p>我们使用idea工具先来创建一个SpringBoot项目，添加的依赖跟<a href="http://www.jianshu.com/p/ac388c3c36c2" target="_blank" rel="noopener">第三章：使用QueryDSL与SpringDataJPA完成Update&amp;Delete</a>一致。为了方便分离文章源码，我们创建完成后把第三章的application.yml配置文件以及pom.xml依赖内容复制到本章项目中（配置内容请参考第三章）。</p>
<h3 id="创建数据表"><a href="#创建数据表" class="headerlink" title="创建数据表"></a>创建数据表</h3><p>我们先来根据一个简单的业务逻辑来创建两张一对多关系的表，下面我们先来创建商品类型信息表，代码如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">-- ----------------------------</span><br><span class="line">-- Table structure for good_types</span><br><span class="line">-- ----------------------------</span><br><span class="line">DROP TABLE IF EXISTS `good_types`;</span><br><span class="line">CREATE TABLE `good_types` (</span><br><span class="line">  `tgt_id` int(11) NOT NULL AUTO_INCREMENT COMMENT &apos;主键自增&apos;,</span><br><span class="line">  `tgt_name` varchar(30) CHARACTER SET utf8 DEFAULT NULL COMMENT &apos;类型名称&apos;,</span><br><span class="line">  `tgt_is_show` char(1) DEFAULT NULL COMMENT &apos;是否显示&apos;,</span><br><span class="line">  `tgt_order` int(2) DEFAULT NULL COMMENT &apos;类型排序&apos;,</span><br><span class="line">  PRIMARY KEY (`tgt_id`)</span><br><span class="line">) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;</span><br></pre></td></tr></table></figure></p>
<p>接下来我们再来创建一个商品基本信息表，表结构如下代码所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">-- ----------------------------</span><br><span class="line">-- Table structure for good_infos</span><br><span class="line">-- ----------------------------</span><br><span class="line">DROP TABLE IF EXISTS `good_infos`;</span><br><span class="line">CREATE TABLE `good_infos` (</span><br><span class="line">  `tg_id` int(11) NOT NULL AUTO_INCREMENT COMMENT &apos;主键自增&apos;,</span><br><span class="line">  `tg_title` varchar(50) CHARACTER SET utf8 DEFAULT NULL COMMENT &apos;商品标题&apos;,</span><br><span class="line">  `tg_price` decimal(8,2) DEFAULT NULL COMMENT &apos;商品单价&apos;,</span><br><span class="line">  `tg_unit` varchar(20) CHARACTER SET utf8 DEFAULT NULL COMMENT &apos;单位&apos;,</span><br><span class="line">  `tg_order` varchar(255) DEFAULT NULL COMMENT &apos;排序&apos;,</span><br><span class="line">  `tg_type_id` int(11) DEFAULT NULL COMMENT &apos;类型外键编号&apos;,</span><br><span class="line">  PRIMARY KEY (`tg_id`),</span><br><span class="line">  KEY `tg_type_id` (`tg_type_id`)</span><br><span class="line">) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;</span><br></pre></td></tr></table></figure></p>
<h3 id="创建实体"><a href="#创建实体" class="headerlink" title="创建实体"></a>创建实体</h3><p>我们对应上面两张表的结构创建两个实体并添加对应的SpringDataJPA注解配置，商品类型实体如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">package com.yuqiyu.querydsl.sample.chapter4.bean;</span><br><span class="line"></span><br><span class="line">import lombok.Data;</span><br><span class="line"></span><br><span class="line">import javax.persistence.*;</span><br><span class="line">import java.io.Serializable;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * ========================</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * User：恒宇少年</span><br><span class="line"> * Date：2017/7/9</span><br><span class="line"> * Time：15:04</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Entity</span><br><span class="line">@Table(name = &quot;good_types&quot;)</span><br><span class="line">@Data</span><br><span class="line">public class GoodTypeBean</span><br><span class="line">    implements Serializable</span><br><span class="line">&#123;</span><br><span class="line">    //主键</span><br><span class="line">    @Id</span><br><span class="line">    @GeneratedValue</span><br><span class="line">    @Column(name = &quot;tgt_id&quot;)</span><br><span class="line">    private Long id;</span><br><span class="line">    //类型名称</span><br><span class="line">    @Column(name = &quot;tgt_name&quot;)</span><br><span class="line">    private String name;</span><br><span class="line">    //是否显示</span><br><span class="line">    @Column(name = &quot;tgt_is_show&quot;)</span><br><span class="line">    private int isShow;</span><br><span class="line">    //排序</span><br><span class="line">    @Column(name = &quot;tgt_order&quot;)</span><br><span class="line">    private int order;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>商品基本信息实体如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">package com.yuqiyu.querydsl.sample.chapter4.bean;</span><br><span class="line"></span><br><span class="line">import lombok.Data;</span><br><span class="line"></span><br><span class="line">import javax.persistence.*;</span><br><span class="line">import java.io.Serializable;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * ========================</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * User：恒宇少年</span><br><span class="line"> * Date：2017/7/9</span><br><span class="line"> * Time：15:08</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Entity</span><br><span class="line">@Table(name = &quot;good_infos&quot;)</span><br><span class="line">@Data</span><br><span class="line">public class GoodInfoBean</span><br><span class="line">    implements Serializable</span><br><span class="line">&#123;</span><br><span class="line">    //主键</span><br><span class="line">    @Id</span><br><span class="line">    @GeneratedValue</span><br><span class="line">    @Column(name = &quot;tg_id&quot;)</span><br><span class="line">    private Long id;</span><br><span class="line">    //商品标题</span><br><span class="line">    @Column(name = &quot;tg_title&quot;)</span><br><span class="line">    private String title;</span><br><span class="line">    //商品价格</span><br><span class="line">    @Column(name = &quot;tg_price&quot;)</span><br><span class="line">    private double price;</span><br><span class="line">    //商品单位</span><br><span class="line">    @Column(name = &quot;tg_unit&quot;)</span><br><span class="line">    private String unit;</span><br><span class="line">    //商品排序</span><br><span class="line">    @Column(name = &quot;tg_order&quot;)</span><br><span class="line">    private int order;</span><br><span class="line">    //类型外键</span><br><span class="line">    @Column(name = &quot;tg_type_id&quot;)</span><br><span class="line">    private Long typeId;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我在商品表内并没有使用类型的实体作为表之间的关联而是只用的具体类型编号，有的时候也是根据你的需求来配置的，如果你每个商品读取基本信息时都需要获取商品的类型，那么这里配置@OneToOne还是比较省事，不需要你再操作多余的查询。</p>
<h3 id="构建QueryDSL查询实体"><a href="#构建QueryDSL查询实体" class="headerlink" title="构建QueryDSL查询实体"></a>构建QueryDSL查询实体</h3><p>下面我们使用maven compile命令来自动生成QueryDSL的查询实体，我们在执行命令的时候会自动去pom.xml配置文件内查找JPAAnnotationProcessor插件，如果你的实体配置了@Entity注解，那么就会自动生成查询实体并将生成的实体放置到target/generated-sources/java内。<br>我们找到idea工具的Maven Projects窗口，如下图1所示：</p>
<p><img src="http://upload-images.jianshu.io/upload_images/4461954-cae4d81842fe54a6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1"><br>我们双击对应的命令就可以执行构建项目了，构建完成的查询实体如下图2所示：<br><img src="http://upload-images.jianshu.io/upload_images/4461954-00533d0ae6859ba6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2"><br>如上图2所示，QueryDSL在生成时会完全根据实体的包来对应创建。</p>
<h3 id="创建控制器"><a href="#创建控制器" class="headerlink" title="创建控制器"></a>创建控制器</h3><p>下面我们来创建一个控制器，我们在控制器内直接编写QueryDSL查询代码，这里就不去根据MVC模式进行编程了，在正式环境下还请大家按照MVC模式来编码。<br>控制器代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line">package com.yuqiyu.querydsl.sample.chapter4.controller;</span><br><span class="line"></span><br><span class="line">import com.querydsl.jpa.impl.JPAQueryFactory;</span><br><span class="line">import com.yuqiyu.querydsl.sample.chapter4.bean.GoodInfoBean;</span><br><span class="line">import com.yuqiyu.querydsl.sample.chapter4.bean.QGoodInfoBean;</span><br><span class="line">import com.yuqiyu.querydsl.sample.chapter4.bean.QGoodTypeBean;</span><br><span class="line">import org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line">import org.springframework.web.bind.annotation.RequestMapping;</span><br><span class="line">import org.springframework.web.bind.annotation.RequestParam;</span><br><span class="line">import org.springframework.web.bind.annotation.RestController;</span><br><span class="line"></span><br><span class="line">import javax.annotation.PostConstruct;</span><br><span class="line">import javax.persistence.EntityManager;</span><br><span class="line">import java.util.List;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * ========================</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * User：恒宇少年</span><br><span class="line"> * Date：2017/7/9</span><br><span class="line"> * Time：15:24</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@RestController</span><br><span class="line">public class GoodController</span><br><span class="line">&#123;</span><br><span class="line"></span><br><span class="line">    @Autowired</span><br><span class="line">    private EntityManager entityManager;</span><br><span class="line"></span><br><span class="line">    //查询工厂实体</span><br><span class="line">    private JPAQueryFactory queryFactory;</span><br><span class="line"></span><br><span class="line">    //实例化控制器完成后执行该方法实例化JPAQueryFactory</span><br><span class="line">    @PostConstruct</span><br><span class="line">    public void initFactory()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;开始实例化JPAQueryFactory&quot;);</span><br><span class="line">        queryFactory = new JPAQueryFactory(entityManager);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @RequestMapping(value = &quot;/selectByType&quot;)</span><br><span class="line">    public List&lt;GoodInfoBean&gt; selectByType</span><br><span class="line">            (</span><br><span class="line">                    @RequestParam(value = &quot;typeId&quot;) Long typeId //类型编号</span><br><span class="line">            )</span><br><span class="line">    &#123;</span><br><span class="line">        //商品查询实体</span><br><span class="line">        QGoodInfoBean _Q_good = QGoodInfoBean.goodInfoBean;</span><br><span class="line">        //商品类型查询实体</span><br><span class="line">        QGoodTypeBean _Q_good_type = QGoodTypeBean.goodTypeBean;</span><br><span class="line">        return</span><br><span class="line">                queryFactory</span><br><span class="line">                .select(_Q_good)</span><br><span class="line">                .from(_Q_good,_Q_good_type)</span><br><span class="line">                .where(</span><br><span class="line">                        //为两个实体关联查询</span><br><span class="line">                        _Q_good.typeId.eq(_Q_good_type.id)</span><br><span class="line">                        .and(</span><br><span class="line">                                //查询指定typeid的商品</span><br><span class="line">                                _Q_good_type.id.eq(typeId)</span><br><span class="line">                        )</span><br><span class="line">                )</span><br><span class="line">                //根据排序字段倒序</span><br><span class="line">                .orderBy(_Q_good.order.desc())</span><br><span class="line">                //执行查询</span><br><span class="line">                .fetch();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>可以看到上面的代码，我们查询了两张表，仅返回了商品信息内的字段（select(_Q_good)）,我们在where条件内进行了这两张表的关联，根据传递的类型编号作为关联商品类型主键（相当于left join），最后根据排序字段进行倒序。</p>
<h1 id="运行测试"><a href="#运行测试" class="headerlink" title="运行测试"></a>运行测试</h1><p>下面我们来运行项目，控制台日志输出内容如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">.....</span><br><span class="line"></span><br><span class="line">  .   ____          _            __ _ _</span><br><span class="line"> /\\ / ___&apos;_ __ _ _(_)_ __  __ _ \ \ \ \</span><br><span class="line">( ( )\___ | &apos;_ | &apos;_| | &apos;_ \/ _` | \ \ \ \</span><br><span class="line"> \\/  ___)| |_)| | | | | || (_| |  ) ) ) )</span><br><span class="line">  &apos;  |____| .__|_| |_|_| |_\__, | / / / /</span><br><span class="line"> =========|_|==============|___/=/_/_/_/</span><br><span class="line"> :: Spring Boot ::        (v1.5.4.RELEASE)</span><br><span class="line"></span><br><span class="line">.....</span><br><span class="line">开始实例化JPAQueryFactory</span><br><span class="line">2017-07-09 15:40:38.454  INFO 11776 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1184ab05: startup date [Sun Jul 09 15:40:36 CST 2017]; root of context hierarchy</span><br><span class="line">2017-07-09 15:40:38.495  INFO 11776 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped &quot;&#123;[/selectByType]&#125;&quot; onto public java.util.List&lt;com.yuqiyu.querydsl.sample.chapter4.bean.GoodInfoBean&gt; com.yuqiyu.querydsl.sample.chapter4.controller.GoodController.selectByType(java.lang.Long)</span><br><span class="line">2017-07-09 15:40:38.498  INFO 11776 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped &quot;&#123;[/error]&#125;&quot; onto public org.springframework.http.ResponseEntity&lt;java.util.Map&lt;java.lang.String, java.lang.Object&gt;&gt; org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)</span><br><span class="line">2017-07-09 15:40:38.498  INFO 11776 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped &quot;&#123;[/error],produces=[text/html]&#125;&quot; onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)</span><br><span class="line">2017-07-09 15:40:38.515  INFO 11776 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]</span><br><span class="line">2017-07-09 15:40:38.515  INFO 11776 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]</span><br><span class="line">2017-07-09 15:40:38.536  INFO 11776 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]</span><br><span class="line">2017-07-09 15:40:38.721  INFO 11776 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup</span><br><span class="line">2017-07-09 15:40:38.723  INFO 11776 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name &apos;dataSource&apos; has been autodetected for JMX exposure</span><br><span class="line">2017-07-09 15:40:38.726  INFO 11776 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Located MBean &apos;dataSource&apos;: registering with JMX server as MBean [com.alibaba.druid.pool:name=dataSource,type=DruidDataSource]</span><br><span class="line">2017-07-09 15:40:38.765  INFO 11776 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)</span><br><span class="line">2017-07-09 15:40:38.769  INFO 11776 --- [           main] c.y.q.s.chapter4.Chapter4Application     : Started Chapter4Application in 3.027 seconds (JVM running for 3.683)</span><br></pre></td></tr></table></figure></p>
<p>可以看到我们在项目启动的时候JPAQueryFactory查询工厂对象就被实例了，接下来我们直接使用JPAQueryFactory实例对象就Ok了。下面我们来访问 : <a href="http://127.0.0.1:8080/selectByType?typeId=1" target="_blank" rel="noopener">http://127.0.0.1:8080/selectByType?typeId=1</a><br>界面输出内容如下图3所示：</p>
<p><img src="http://upload-images.jianshu.io/upload_images/4461954-df4c7dea32f63693.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图3"><br>下面我们来看下控制台输出的SQL，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">Hibernate: </span><br><span class="line">    select</span><br><span class="line">        goodinfobe0_.tg_id as tg_id1_0_,</span><br><span class="line">        goodinfobe0_.tg_order as tg_order2_0_,</span><br><span class="line">        goodinfobe0_.tg_price as tg_price3_0_,</span><br><span class="line">        goodinfobe0_.tg_title as tg_title4_0_,</span><br><span class="line">        goodinfobe0_.tg_type_id as tg_type_5_0_,</span><br><span class="line">        goodinfobe0_.tg_unit as tg_unit6_0_ </span><br><span class="line">    from</span><br><span class="line">        good_infos goodinfobe0_ cross </span><br><span class="line">    join</span><br><span class="line">        good_types goodtypebe1_ </span><br><span class="line">    where</span><br><span class="line">        goodinfobe0_.tg_type_id=goodtypebe1_.tgt_id </span><br><span class="line">        and goodtypebe1_.tgt_id=? </span><br><span class="line">    order by</span><br><span class="line">        goodinfobe0_.tg_order desc</span><br></pre></td></tr></table></figure></p>
<p>QueryDSL自动生成的SQL采用了Cross Join 获取两张表的《笛卡尔集》然后根据select内配置的实体进行返回字段，我们使用 where goodinfobe0_.tg_type<em>id=goodtypebe1</em>.tgt<em>id 代替了on goodinfobe0</em>.tg_type<em>id=goodtypebe1</em>.tgt_id实现了相同的效果。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>本章的内容比较简单，我们使用QueryDSL完成了两个实体关联查询并返回单实体实例的方法，QueryDSL内也有LeftJoin、InnerJoin等关联查询不过都是基于具体实体类型来完成的，本章就不做解释了，用起来比较繁琐复杂它们遵循的是HQL语法。</p>
<p>本章代码已经上传到码云：<br>SpringBoot配套源码地址：<a href="https://gitee.com/hengboy/spring-boot-chapter" target="_blank" rel="noopener">https://gitee.com/hengboy/spring-boot-chapter</a><br>SpringCloud配套源码地址：<a href="https://gitee.com/hengboy/spring-cloud-chapter" target="_blank" rel="noopener">https://gitee.com/hengboy/spring-cloud-chapter</a><br>SpringBoot相关系列文章请访问：<a href="http://www.jianshu.com/p/9a08417e4e84" target="_blank" rel="noopener">目录：SpringBoot学习目录</a><br>QueryDSL相关系列文章请访问：<a href="http://www.jianshu.com/p/99a5ec5c3bd5" target="_blank" rel="noopener">QueryDSL通用查询框架学习目录</a><br>SpringDataJPA相关系列文章请访问：<a href="http://www.jianshu.com/p/615ed9c1fe84" target="_blank" rel="noopener">目录：SpringDataJPA学习目录</a><br>感谢阅读！<br>欢迎加入QQ技术交流群，共同进步。<br><img src="http://upload-images.jianshu.io/upload_images/4461954-f1d4cb64234b160a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="QQ技术交流群"></p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">


    <div class="bdsharebuttonbox">
    <a href="#" class="bds_more" data-cmd="more">分享到：</a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间">QQ空间</a>
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博">新浪微博</a>
    <a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博">腾讯微博</a>
    <a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网">人人网</a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信">微信</a>
</div>
<script>
window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{"bdSize":16}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>
<style>
    .bdshare_popup_box {
        border-radius: 4px;
        border: #e1e1e1 solid 1px;
    }
    .bdshare-button-style0-16 a,
    .bdshare-button-style0-16 .bds_more {
        padding-left: 20px;
        margin: 6px 10px 6px 0;
    }
    .bdshare_dialog_list a,
    .bdshare_popup_list a,
    .bdshare_popup_bottom a {
        font-family: 'Microsoft Yahei';
    }
    .bdshare_popup_top {
        display: none;
    }
    .bdshare_popup_bottom {
        height: auto;
        padding: 5px;
    }
</style>


</div>

            
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
        <a href="/querydsl-chapter-5/" id="article-nav-newer" class="article-nav-link-wrap">
            <strong class="article-nav-caption">上一篇</strong>
            <div class="article-nav-title">
                
                    第五章：使用QueryDSL与SpringDataJPA实现查询返回自定义对象
                
            </div>
        </a>
    
    
        <a href="/querydsl-chapter-3/" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">下一篇</strong>
            <div class="article-nav-title">第三章：使用QueryDSL与SpringDataJPA完成Update&amp;Delete</div>
        </a>
    
</nav>


    
</article>


    
    

</section>
            
			
				
<aside id="sidebar">
   
        
    <div class="widget-wrap">
        <h3 class="widget-title">最新文章</h3>
        <div class="widget">
            <ul id="recent-post" class="no-thumbnail">
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-52/" class="title">第五十二章：基于SpringBoot2使用Rest访问MongoDB数据</a></p>
                            <p class="item-date"><time datetime="2018-04-21T16:00:00.000Z" itemprop="datePublished">2018-04-22</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-51/" class="title">第五十一章：基于SpringBoot2 &amp; MongoDB完成自动化集成</a></p>
                            <p class="item-date"><time datetime="2018-04-15T16:00:00.000Z" itemprop="datePublished">2018-04-16</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-50/" class="title">第五十章：SpringBoot2.0新特性 - 岂止至今最简单redis缓存集成</a></p>
                            <p class="item-date"><time datetime="2018-04-14T16:00:00.000Z" itemprop="datePublished">2018-04-15</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-49/" class="title">第四十九章：SpringBoot2.0新特性 - 你get到WebMvcConfigurer两种配置方式了吗？</a></p>
                            <p class="item-date"><time datetime="2018-03-16T16:00:00.000Z" itemprop="datePublished">2018-03-17</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-48/" class="title">第四十八章：SpringBoot2.0新特性 - RabbitMQ信任package设置</a></p>
                            <p class="item-date"><time datetime="2018-03-12T16:00:00.000Z" itemprop="datePublished">2018-03-13</time></p>
                        </div>
                    </li>
                
            </ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">分类</h3>
        <div class="widget">
            <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/QueryDSL-核心技术/">QueryDSL 核心技术</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a><span class="category-list-count">36</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">归档</h3>
        <div class="widget">
            <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/04/">四月 2018</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">三月 2018</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/01/">一月 2018</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/12/">十二月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/11/">十一月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/10/">十月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/09/">九月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/08/">八月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/07/">七月 2017</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/06/">六月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/05/">五月 2017</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/04/">四月 2017</a><span class="archive-list-count">5</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签</h3>
        <div class="widget">
            <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/QueryDSL/">QueryDSL</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/SpringBoot/">SpringBoot</a><span class="tag-list-count">43</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签云</h3>
        <div class="widget tagcloud">
            <a href="/tags/QueryDSL/" style="font-size: 10px;">QueryDSL</a> <a href="/tags/SpringBoot/" style="font-size: 20px;">SpringBoot</a>
        </div>
    </div>

    
        
    <div class="widget-wrap widget-list">
        <h3 class="widget-title">链接</h3>
        <div class="widget">
            <ul>
                
                    <li>
     				<a href="http://hexo.io" target="_blank">Hexo</a>
					</li>
                
            </ul>
        </div>
    </div>


    
    <div id="toTop" class="fa fa-angle-up"></div>
</aside>

				
        </div>
        <!--引入不蒜子-->
<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<footer id="footer">
    <div class="outer">
        <div id="footer-info" class="inner">
            <span  id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
            &copy; 2017 - 2018 恒宇少年 - 版权所有<br>
        </div>
    </div>
</footer>

        


    
        <script src="/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    
    



<!-- Custom Scripts -->
<script src="/js/main.js"></script>

    </div>
</body>
</html>